<template>
	<view class="preview" v-if="currentInfo">
		<swiper :circular="true" :current="currentIndex" @change="swiperChange">
			<swiper-item class="" v-for="(item,index) in classList" :key="item._id">
				<image v-if="readImgs.includes(index)" @click="maskChange" :src="item.picurl" mode="aspectFill"></image>
			</swiper-item>
		</swiper>
		<!-- {{readImgs}} -->
		<view class="mask" v-show="maskState">
			<view class="goBack" @click="goBack" :style="{top:getStatusBarHeight() + 'px'}">
				<uni-icons type="back" color="#fff" size="20"></uni-icons>
			</view>
			<view class="count">{{currentIndex+1}} / {{classList.length}}</view>
			<view class="time">
				<uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat :date="new Date()" format="MM月dd日"></uni-dateformat>
			</view>
			<view class="footer">
				<view class="box" @click="clickinfo">
					<uni-icons type="info" size="28"></uni-icons>
					<view class="text">信息</view>
				</view>
				<view class="box" @click="clickScore">
					<uni-icons type="star" size="28"></uni-icons>
					<view class="text">{{currentInfo.score}}</view>
				</view>
				<view class="box" @click="clickDownload">
					<uni-icons type="download" size="23"></uni-icons>
					<view class="text">下载</view>
				</view>
			</view>
		</view>

		<uni-popup ref="infoPopup" type="bottom" background-color="#fff">
			<view class="infoPopup">
				<view class="popHeader">
					<view></view>
					<view class="title">壁纸信息</view>
					<view class="close" @click="clickinfoClose">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<scroll-view scroll-y="true">
					<view class="content">
						<view class="row">
							<view class="label">壁纸ID：</view>
							<!-- #ifdef MP-WEIXIN -->
							<text class="value" user-select>{{currentInfo._id}}</text>
							<!-- #endif -->
							<!-- #ifndef MP-WEIXIN -->
							<text class="value" selectable>{{currentInfo._id}}</text>
							<!-- #endif -->
						</view>
						<view class="row">
							<view class="label">分类：</view>
							<text class="value class">fenlei</text>
						</view>
						<view class="row">
							<view class="label">发布者：</view>
							<text class="value">{{currentInfo.nickname}}</text>
						</view>
						<view class="row">
							<view class="label">评分：</view>
							<view class="value roteBox">
								<uni-rate readonly touchable :value="currentInfo.score" size="16"></uni-rate>
								<text class="score">{{currentInfo.score}}</text>
							</view>
						</view>
						<view class="row">
							<view class="label">摘要：</view>
							<text class="value">
								{{currentInfo.description}}
							</text>
						</view>
						<view class="row">
							<view class="label">标签：</view>
							<view class="value tabs">
								<view class="tab" v-for="(item,index) in currentInfo.tabs" :key="index">
									{{item}}
								</view>
							</view>
						</view>
						<view class="copyright">
							声明:本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸，维护您的权益。
						</view>
					</view>
				</scroll-view>
			</view>
		</uni-popup>

		<uni-popup ref="scorePopup" type="center" :is-mask-click="false">
			<view class="scorePopup">
				<view class="popHeader">
					<view></view>
					<view class="title">{{isScore?'评分过了~':'评分壁纸'}}</view>
					<view class="close" @click="clickScoreClose">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>

				<view class="content">
					<uni-rate v-model="userScore" :allowHalf="true" :disabled="isScore"></uni-rate>
					<text class="text">{{userScore}}</text>
				</view>

				<view class="footer">
					<button @click="submitScore" :disabled="!userScore || isScore" type="default" size="mini"
						plain>确认评分</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';

	import {
		getStatusBarHeight
	} from "@/utils/system.js"

	import {
		onLoad,
		onShareAppMessage,
		onShareTimeline
	} from "@dcloudio/uni-app"

	import {
		apiGetSetupScore,
		apiWriteDowload,
		apiDetailWall
	} from "@/api/apis.js"



	// 详情页面渲染
	// 声明一个响应式数组用于存储分类列表数据
	const classList = ref([])
	// 从本地存储中获取分类列表数据，如果没有则默认为空数组
	const storgClassList = uni.getStorageSync("storgClassList") || [];
	console.log(storgClassList)
	// 处理图片URL，将_small.webp替换为.jpg，并赋值给classList
	classList.value = storgClassList.map(item => {
		return {
			...item, // 保留item中的所有属性
			picurl: item.smallPicurl.replace("_small.webp", ".jpg") // 修改图片URL格式
		}
	});
	console.log(classList);

	// 图片信息
	// 声明一个响应式数组用于存储当前显示的图片信息
	const currentInfo = ref(null);

	// 接收分类页classlist参数
	// 声明一个响应式变量用于存储从分类页传入的ID
	const currentId = ref(null);
	// 页面加载时执行的函数，用于接收传递的id参数，找到对应分类，设置currentIndex，并获取当前图片信息，最后调用图片预加载函数
	onLoad(async (e) => {
		currentId.value = e.id;

		if (e.type == 'share') {
			let res = await apiDetailWall({
				id: currentId.value
			});
			classList.value = res.data.map(item => {
				return {
					...item, // 保留item中的所有属性
					picurl: item.smallPicurl.replace("_small.webp", ".jpg") // 修改图片URL格式
				}
			});
			console.log(res)
		}

		currentIndex.value = classList.value.findIndex(item => item._id == currentId.value);
		currentInfo.value = classList.value[currentIndex.value];
		console.log(currentInfo.value)
		readImgsFun();
	});



	// 滑动事件，显示当前图片序号
	// 声明一个响应式变量用于记录当前显示图片的索引
	const currentIndex = ref(0);

	// 滑动事件处理器，根据滑动改变currentIndex的值，更新currentInfo，并调用图片预加载函数
	const swiperChange = (e) => {
		currentIndex.value = e.detail.current;
		currentInfo.value = classList.value[currentIndex.value];
		readImgsFun();
		console.log(currentInfo.value); // 打印当前图片信息到控制台
	};

	// 预加载图片
	// const readImgs = ref([])

	// function readImgsFun() {
	// 	readImgs.value.push(
	// 		currentIndex.value <= 0 ? classList.value.length - 1 : currentIndex.value - 1,
	// 		currentIndex.value,
	// 		currentIndex.value >= classList.value.length - 1 ? 0 : currentIndex.value + 1,
	// 	)
	// 	readImgs.value = [...new Set(readImgs.value)]
	// }

	// 预加载图片
	// 声明一个响应式数组用于存储需要预加载的图片索引
	const readImgs = ref([]);

	// 预加载图片的函数，计算当前图片前一张、当前张和后一张的索引，并确保这些索引在classList范围内，然后去除重复并更新readImgs
	// 定义一个用于预加载图片的函数
	function readImgsFun() {
		// 计算当前图片的前一张索引
		// 如果当前索引为0（即第一张图片），则'prevIndex'应为分类列表的最后一张图片（数组长度减1）
		// 否则，'prevIndex'为当前索引减1
		const prevIndex = currentIndex.value <= 0 ? classList.value.length - 1 : currentIndex.value - 1;

		// 计算当前图片的后一张索引
		// 如果当前索引等于分类列表的最后一张图片（数组长度减1），则'nextIndex'应为分类列表的第一张图片（索引0）
		// 这是为了实现轮播图效果，让用户在浏览到最后时能平滑地回到第一张
		// 否则，'nextIndex'为当前索引加1
		const nextIndex = currentIndex.value >= classList.value.length - 1 ? 0 : currentIndex.value + 1;

		// 创建一个新的数组，包含当前图片及其前后各一张图片的索引
		// 这样做是为了预加载这些图片，提高用户体验，使得用户滑动时图片能快速显示
		readImgs.value = [prevIndex, currentIndex.value, nextIndex];

		// 使用Set数据结构来去除数组中的重复元素
		// 因为在列表的开头和结尾切换时（如从最后一张到第一张），可能会有相同的索引值
		// Set会自动去除重复项，确保每个索引值只出现一次
		// 然后通过扩展运算符(...)将Set转换回数组，以更新'readImgs.value'
		readImgs.value = [...new Set(readImgs.value)];
	}


	// 点击打开弹窗
	const infoPopup = ref(null)
	const clickinfo = () => {
		infoPopup.value.open()
	}
	// 关闭信息弹窗
	const clickinfoClose = () => {
		infoPopup.value.close()
	}


	// 评分值
	const userScore = ref()
	const isScore = ref(false)

	// 评分弹窗
	const scorePopup = ref(null)
	const clickScore = () => {
		if (currentInfo.value.userScore) {
			isScore.value = true;
			userScore.value = currentInfo.value.userScore;
		}
		scorePopup.value.open()
	}
	// 关闭评分弹窗
	const clickScoreClose = () => {
		scorePopup.value.close()
		userScore.value = 0
		isScore.value = false
	}
	// 确认评分
	const submitScore = async () => {
		uni.showLoading({
			title: "加载中。。"
		})
		let {
			classid,
			_id: wallId
		} = currentInfo.value

		let res = await apiGetSetupScore({
			classid,
			wallId,
			userScore: userScore.value
		})
		uni.hideLoading()
		if (res.errCode === 0) {
			uni.showToast({
				title: "评分成功",
				icon: 'none'
			})

			classList.value[currentIndex.value].userScore = userScore.value
			uni.setStorageSync("storgClassList", classList.value)
			clickScoreClose()
		}
		// console.log(userScore.value)
		console.log(res)
	}


	// 遮罩状态
	const maskState = ref(true)
	const maskChange = () => {
		maskState.value = !maskState.value
	}

	// 点击下载
	const clickDownload = async () => {
		// #ifdef H5
		uni.showModal({
			content: "请长按保存图片",
			showCancel: false
		})
		// #endif

		// #ifndef H5

		try {
			uni.showLoading({
				title: "下载中",
				mask: true
			})

			// 写入数据库
			let {
				classid,
				_id: wallId
			} = currentInfo.value

			let res = await apiWriteDowload({
				classid,
				wallId
			})
			console.log(res)
			if (res.errCode != 0) {
				throw res;
			}
			// return;

			uni.getImageInfo({
				src: currentInfo.value.picurl,
				success: (res) => {
					uni.saveImageToPhotosAlbum({
						filePath: res.path,
						success: (e) => {
							console.log(e)
						},
						fail: (err) => {

							if (err.errMsg == "saveImageToPhotosAlbum:fail cancel") {
								uni.showToast({
									title: "保存失败，请点击重新下载",
									icon: "none"
								})
								return;
							}
							console.log(err)

							uni.showModal({
								title: "授权提示",
								content: "需要授权保存图片",
								success: (res) => {
									if (res.confirm) {
										console.log("确认授权了")
										uni.openSetting({
											success: (res) => {
												console.log(res)
												console.log(res
													.authSetting[
														'scope.writePhotosAlbum'
													])
												if (res
													.authSetting[
														'scope.writePhotosAlbum'
													]) {
													uni.showToast({
														title: "获取授权成功",
														icon: "none"
													})
												} else {
													uni.showToast({
														title: "获取授权失败",
														icon: "none"
													})
												}
											}
										})
									}
								}
							})
						},
						complete: () => {
							uni.hideLoading()
						}
					})
				}
			})
		} catch (e) {
			console.log(e)
			uni.hideLoading()
		}



		// #endif
	}


	// 分享好友
	onShareAppMessage((e) => {
		console.log(e)
		return {
			title: '虾米壁纸分类',
			path: '/pages/preview/preview?id=' + currentId.value + '&type=share'
		}
	})

	// 分享朋友圈
	onShareTimeline(() => {
		return {
			title: '虾米壁纸分类',
			query: 'id=' + currentId.value

		}
	})


	// 返回按键
	const goBack = () => {

		console.log(getCurrentPages());
		
		// #ifdef H5
			// H5端页面刷新之后页面栈会消失，此时navigateBack不能返回，如果一定要返回可以使用history.back()导航到浏览器的其他历史记录。
			history.back();
		// #endif
		
		// #ifndef H5
		uni.navigateBack({
			delta: 1,
			success() {
				console.log(222)
			},
			fail() {
				// 分享页面返回键失败的情况,返回首页
				console.log(3333)
				uni.reLaunch({
					url: "/pages/index/index"
				})
			}
		})
		// #endif

	}
</script>

<style lang="scss" scoped>
	.preview {
		width: 100%;
		height: 100vh;
		position: relative;

		swiper {
			width: 100%;
			height: 100%;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.mask {
			&>view {
				position: absolute;
				margin: auto;
				left: 0;
				right: 0;
				color: #fff;
				width: fit-content;
			}

			.goBack {
				width: 68rpx;
				height: 68rpx;
				background: rgba(0, 0, 0, 0.5);
				left: 30rpx;
				top: 0;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 100rpx;
				margin-left: 0;
				backdrop-filter: blur(10rpx);
				border: 1rpx solid rgba(0, 0, 0, 0.3);
			}

			.count {
				top: 10vh;
				background: rgba(0, 0, 0, 0.3);
				font-size: 28rpx;
				border-radius: 40rpx;
				padding: 8rpx 28rpx;
				backdrop-filter: blur(10rpx);
			}

			.time {
				font-size: 140rpx;
				top: calc(10vh + 80rpx);
				font-weight: 100;
				line-height: 1em;
				text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
			}

			.date {
				font-size: 34rpx;
				top: calc(10vh + 230rpx);
				text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
			}

			.footer {
				background: rgba(255, 255, 255, 0.8);
				bottom: 10vh;
				width: 65vw;
				height: 120rpx;
				border-radius: 60rpx;
				color: #000;
				display: flex;
				justify-content: space-around;
				align-items: center;
				text-shadow: 0 2rpx rgba(0, 0, 0, 0.1);
				backdrop-filter: blur(20rpx);

				.box {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					padding: 2rpx 12rpx;

					// border: 1rpx solid red;
					.text {
						font-size: 26rpx;
						color: $text-font-color-2;
					}
				}
			}
		}

		.popHeader {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.title {
				color: $text-font-color-2;
				font-size: 26rpx;
			}

			.close {
				// border: 1rpx solid red;
				padding: 6rpx;
			}
		}


		.infoPopup {
			background: #fff;
			padding: 30rpx;
			border-radius: 30rpx 30rpx 0 0;
			overflow: hidden;

			scroll-view {
				max-height: 60vh;

				.content {
					.row {
						display: flex;
						padding: 16rpx 0;
						line-height: 1.7em;

						.label {
							color: $text-font-color-3;
							width: 140rpx;
							text-align: right;
							font-size: 30rpx;
						}

						.value {
							flex: 1;
							width: 0;
						}

						.roteBox {
							display: flex;
							align-items: center;

							// background: red;
							.score {
								font-size: 26rpx;
								color: $text-font-color-2;
								padding-left: 20rpx;
							}
						}

						.tabs {
							display: flex;
							flex-wrap: wrap;

							.tab {
								// background: red;
								border: 1px solid $brand-theme-color;
								color: $brand-theme-color;
								font-size: 22rpx;
								padding: 10rpx 30rpx;
								margin: 0 10rpx 10rpx 0;
								border-radius: 40rpx;
								line-height: 1em;
								margin: 0 10rpx 10rpx 0;
							}
						}

						.class {
							color: $brand-theme-color;
						}
					}

					.copyright {
						font-size: 28rpx;
						padding: 20rpx;
						background: #f6f6f6;
						color: #666;
						border-radius: 10rpx;
						margin: 20rpx 0;
						line-height: 1.6em;
					}
				}
			}
		}


		.scorePopup {
			background: #fff;
			padding: 30rpx;
			width: 70vw;
			border-radius: 30rpx;

			.content {
				padding: 30rpx 0;
				display: flex;
				justify-content: center;
				align-items: center;

				.text {
					color: #FFCA3E;
					padding-left: 10rpx;
					width: 80rpx;
					line-height: 1em;
					text-align: right;
				}
			}

			.footer {
				padding: 10rpx 0;
				display: flex;
				align-items: center;
				justify-content: center;

			}
		}
	}
</style>